import axios from 'axios';
import { getToken, removeStorage } from '@/utils/localstorage'
import { message, Modal } from 'antd';

const instance = axios.create({
    baseURL: "http://xr7c3frtb1fg-7360.beijing-01.dayunet.com:80/api",
    timeout: 500000,
    headers: {
        'Content-Type': "application/json;charset=utf-8"
    }
})

//添加拦截
instance.interceptors.request.use(config => {
    const token = getToken();
    
    // 在请求头中设置token
    config.headers['token'] = token;
    config.headers['Authorization'] = `Bearer ${token}`;
    
    return config;
}, error => {
    return Promise.reject(error);
})

instance.interceptors.response.use(res => {
    console.log("返回数据", res)
    //token无效，跳转到登录页面
    if (res.data.code === 407) {
        Modal.error({
            title: '登录失效',
            content: "token无效或者登录过期，将跳转到登录页面",
            onOk: () => {
                removeStorage('token')
                removeStorage('user')
                window.location.href = '/'
            }
        });
        return Promise.reject('登录失效');
    }
    if (res.data.code === 5002) {
        Modal.error({
            title: '无权访问',
            content: '您没权限访问此页面，请联系管理员！将为您跳转到首页！',
            onOk: () => {
                window.location.href = '/'
            }
        });
        return Promise.reject('无权访问');
    }

    return res.data;
}, error => {
    console.log("返回错误" + error)
    // 统一错误处理
    let errorMessage = '网络请求失败';
    if (error.response) {
        // 服务器返回错误状态码
        switch (error.response.status) {
            case 400:
                errorMessage = '请求错误';
                break;
            case 401:
                errorMessage = '未授权，请登录';
                // 跳转到登录页
                removeStorage('token');
                removeStorage('user');
                window.location.href = '/';
                break;
            case 403:
                errorMessage = '拒绝访问';
                break;
            case 404:
                errorMessage = '请求地址不存在';
                break;
            case 500:
                errorMessage = '服务器内部错误';
                break;
            default:
                errorMessage = `服务器错误 (${error.response.status})`;
        }
    } else if (error.request) {
        // 请求发出但没有收到响应
        errorMessage = '网络连接失败，请检查网络';
    } else {
        // 请求配置出错
        errorMessage = error.message;
    }

    message.error(errorMessage);
    return Promise.reject(errorMessage);
})

export default instance;
